package udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/13
 * Time:21:07
 **/

public class UDPClient {
    /**
     * 客户端
     */
    //服务器IP
    private static final String ip = "127.0.0.1";
    //服务器端口号
    private static final int port = 9001;
    //数据最大长度
    private static final int bleng = 1024;
    public static void main(String[] args) throws IOException {
        //1.启动客户端
        DatagramSocket client = new DatagramSocket();//不需要端口号
        System.out.println("客户端启动成功！");
        //发送消息
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("->");
            String msg = scanner.nextLine();
            //2.给服务器端发送消息
            DatagramPacket clientPacket = new DatagramPacket(
                    msg.getBytes(),
                    msg.getBytes().length,
                    InetAddress.getByName(ip),
                    port
            );
            //发送
            client.send(clientPacket);
            // 3.接收服务器的返回信息
            DatagramPacket serPacket = new DatagramPacket(
                    new byte[bleng],
                    bleng
            );
            //接收
            client.receive(serPacket);
            // 接收到服务器端返回信息
            String serMsg = new String(serPacket.getData());
            System.out.println("服务器:"+serMsg);
        }
    }
}
